import axios from 'axios'
import Router from 'next/router'
import { localname } from '../config/host.config'
// 创建axios实例
const service = axios.create({
    baseURL: process.env.BASE_API, // node环境的不同，对应不同的baseURL
    timeout: 5000, // 请求的超时时间
    withCredentials: true // 允许携带cookie
})

// 发送请求前处理request的数据
axios.defaults.transformRequest = [function (data) {
    let newData = ''
    for (let k in data) {
        newData += encodeURIComponent(k) + '=' + encodeURIComponent(data[k]) + '&'
    }
    return newData
}]

// request拦截器
service.interceptors.request.use(
    config => {
        return config
    },
    error => {
        return Promise.reject(error.response.data) // 返回接口返回的错误信息
    }
)

// response拦截器
service.interceptors.response.use(
    response => {
        return response
    },
    error => {
        switch (error.response.status) {
            case 302:
                // 跳转到首页
                if (Router.router.pathname === '/login' || Router.router.pathname === '/register' || Router.router.pathname === '/article') break
                if (Router.router.pathname !== '/' && Router.router.pathname !== '/index') {
                    window.open(localname + '/', '_self')
                }
        }
        return Promise.reject(error)
    }
)
export default service